package com.example.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.demo.entity.Partner;
import com.example.demo.entity.PartnerRequest;
import com.example.demo.mapper.PartnerMapper;
import com.example.demo.mapper.PartnerRequestMapper;
import com.example.demo.service.PartnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class PartnerServiceImpl extends ServiceImpl<PartnerRequestMapper, PartnerRequest> implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    @Override
    public List<PartnerRequest> getReceivedRequests(Integer userId) {
        return baseMapper.selectList(
                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<PartnerRequest>().eq("receiver_id", userId)
        );
    }

    @Override
    public Boolean sendRequest(PartnerRequest request) {
        long count = partnerMapper.selectCount(new QueryWrapper<Partner>()
                .eq("user_id", request.getSenderId())
                .eq("partner_id", request.getReceiverId()));
        if (count > 0) {
            return false; // 已存在搭子关系
        }
        return baseMapper.insert(request) > 0;
    }

    @Override
    public Boolean handleRequest(Integer id, String status) {
        PartnerRequest request = baseMapper.selectById(id);
        if (request == null) return false;
        request.setStatus(status);

        if ("accepted".equals(status)) {
            Partner partner = new Partner();
            partner.setUser_id(request.getSenderId());
            partner.setPartner_id(request.getReceiverId());
            partner.setCreate_time(new java.util.Date());
            partnerMapper.insert(partner);
        }
        return baseMapper.updateById(request) > 0;
    }

    @Override
    public List<Partner> getPartnerList(Integer userId) {
        return partnerMapper.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<Partner>().eq("user_id", userId));
    }

    @Override
    public List<PartnerRequest> getSentRequests(Integer userId) {
        return partnerMapper.selectSentRequestsByUserId(userId);
    }
}
